<?php
/**
 * Users Model. Provides an API for users management
 *
 * @author Konstantin Shamko <konstantin.shamko@gmail.com> 
 * @version 0.0.1
 * @copyright  Copyright (c) 2009 Konstantin Shamko
 * @category VaselinEngine
 * @package Usermanagement Module
 * @subpackage Model
 * @license  New BSD License
 * 
 */
class Models_Usermanagement_Users extends Bel_Model_Abstract {

	/**
	 * Array of many-to-one references with groups' table
	 *
	 * @var array
	 */	
	protected $_referenceMap = array (
									'group' => 
											array ('columns' => 'user_group_id',
												   'refTableClass' => 'Models_Usermanagement_Groups',
									   			   'refColumns' => 'user_group_id'
									   			   )													
									);
	/**
	 * Constructor. Sets table name & primary key
	 *
	 * @param array $array - see Zend_Db_Table_Abstract for details
	 */	
	public function __construct($array = array()) {
		$this->_name = TABLE_PREFIX . 'users';
		$this->_primary = array ('user_id' );
		parent::__construct ( $array );
	}

	/**
	 * Prepares select query for getAll() method. This query should return users with their group info
	 *
	 * @return Zend_Db_Select
	 */
	protected function _selectQuery(){
		$oGroups = new Models_Usermanagement_Groups();
		return $this->_db->select()->from(array('u'=>$this->_name))->joinLeft(array('g'=>$oGroups->info('name')),'u.user_group_id=g.user_group_id');		 
	}
	
	/**
	 * Returns user by email
	 *
	 * @param string $email
	 * @return Zend_Db_Table_Row
	 */
	public function getUserByEmail($email) {
		$row = $this->fetchRow ( "user_email = '$email'" );
		if (! $row) {
			return false;
		}
		return $row;
	}
	
	/**
	 * Returns user by id
	 *
	 * @param int $id
	 * @return array
	 */
	public function getUserById($id) {
		$row = $this->find ( $id )->current ();
		if ($row) {
			return $row;
		} else {
			return false;
		}
	}
		
	/**
	 * Activates user
	 *
	 * @param string $code - activation code
	 * @return bool - true if activated
	 */
	public function activateUser($code) {
		$row = $this->fetchRow ( 'user_confirmation_code=\'' . $code . '\' and user_active=0' );
		if ($row) {
			$row->user_confirmation_code = null;
			$row->user_active = 1;
			$row->save ();
			return true;
		} else
			return false;
	}
	
	/**
	 * Returns user for reseting password 
	 *
	 * @param string $email
	 * @param string $code - validation code. could be fount in a mailbox
	 * @return Zend_Db_Table_Row
	 */
	public function getUserForResetPass( $code) {
		$w1 = new Zend_Db_Expr ( "md5(concat(user_email,user_id))='$code'" );
		$where = $w1->__toString () . " and user_confirmation_code='$code'";
		$user = $this->fetchRow ( ( string ) $where );
		if ($user) {
			return $user;
		} else {
			return false;
		}
	}
}
